/*
  * Mirante Tecnologia
  * Copyright 2010, Mirante Informatica LTDA, 
  * and individual contributors as indicated by the @authors tag
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
package com.miranteinfo.seam.framework.service;

import org.jboss.seam.annotations.intercept.AroundInvoke;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.intercept.InvocationContext;
import org.jboss.seam.transaction.Transaction;

/**
 * Intereptor responsave por efetuar todo o controle transacional da camada de negocio (Service).
 * 
 * @author lucas lins
 * 
 */
public class TransactionSupportInterceptor{
	
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// ATTRIBUTES
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	
	private static final String TRANSACTION_SUPPORT_STARTED = "MIRSEAM_TRANSACTION_SUPPORT_STARTED";
	
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// PUBLIC METHODS
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	
	@AroundInvoke
	public Object intercept(InvocationContext invocation) throws Exception {
		
		if(Contexts.getEventContext().isSet(TRANSACTION_SUPPORT_STARTED) || !Transaction.instance().isActive()) return invocation.proceed();
		
		Contexts.getEventContext().set(TRANSACTION_SUPPORT_STARTED, true);
		ServiceSupport service = (ServiceSupport)invocation.getTarget();
		
		Object returnedValue;
		
		try{
			returnedValue = invocation.proceed();
			service.flush();
			service.raiseEvents();
		}finally{
			Contexts.getEventContext().remove(TRANSACTION_SUPPORT_STARTED);
		}
		
		return returnedValue;
	}
}
